package com.example.springboot.web.common.ex;

import com.example.springboot.web.common.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.example.springboot.web.common.ex.GlobalErrorCodeConstants.BAD_REQUEST;
import static com.example.springboot.web.common.ex.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;

/**
 * @author lei yu
 * @date 2024/05/20
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R<?> exceptionHandler(HttpServletRequest req, Throwable ex) {

        log.warn("[globalExceptionHandler] {}", ExceptionUtils.getMessage(ex));

        // 处理 SpringMVC 参数校验不正确
        if (ex instanceof MethodArgumentNotValidException e) {
            String errorMessage = e.getBindingResult().getAllErrors().getFirst().getDefaultMessage();
            return R.error(BAD_REQUEST.getCode(), String.format("请求参数不正确：%s", errorMessage));
        }

        if (log.isInfoEnabled()) {
            log.info("[兜底异常，打印堆栈] {}", ExceptionUtils.getStackTrace(ex));
        }

        // 处理系统异常，兜底处理所有的一切
        return R.error(INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMessage());
    }
}
